package com.xinlianshiye.im.service.impl;

import com.xinlianshiye.clouds.common.exception.WebMessageExceptionBuilder;
import com.xinlianshiye.im.bean.App;
import com.xinlianshiye.im.dao.AppDao;
import com.xinlianshiye.im.dao.UserDao;
import com.xinlianshiye.im.service.AppService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;

@Service
@Slf4j
public class AppServiceImpl implements AppService {

    private final UserDao userDao;
    private final AppDao appDao;
    private final WebMessageExceptionBuilder exceptionBuilder;

    public AppServiceImpl(UserDao userDao, AppDao appDao, WebMessageExceptionBuilder exceptionBuilder) {
        this.userDao = userDao;
        this.appDao = appDao;
        this.exceptionBuilder = exceptionBuilder;
    }

    public App getOrElseThrow(Integer id) {
        return appDao.findById(id).orElseThrow(() -> exceptionBuilder.build("应用不存在"));
    }

    @Override
    public App save(App params) {
        App app;
        if (params.getId() != null) {
            app = getOrElseThrow(params.getId());
        } else {
            app = new App();
        }
        app.setAppId(params.getAppId());
        app.setName(params.getName());
        app.setSecret(params.getSecret());
        return appDao.save(app);
    }

    @Override
    public List<App> list() {
        return appDao.findAll();
    }

    @Override
    public void delete(Integer id) {
        App app = getOrElseThrow(id);
        boolean exists = userDao.existsByApp(app);
        if(exists) {
            throw exceptionBuilder.build("该应用已经关联了用户， 不能删除");
        } else {
            appDao.delete(app);
        }
    }

    /**
     * 通过appId或者alias获取WxApp对象
     */
    @Override
    public App get(String appId) {
        return appDao.findByAppId(appId).orElseThrow(() -> {
            log.warn("appId为[{}]的应用不存在", appId);
            return exceptionBuilder.build("应用不存在");
        });
    }

    public static final String APP_ID = "client";

    @Override
    public String getAppId(Session session) {
        String appId = (String) session.getUserProperties().get(APP_ID);
        if (appId != null) {
            return get(appId).getAppId();
        } else {
            return null;
        }
    }

    @Override
    public void setAppId(Session session, String appId) {
        session.getUserProperties().put(APP_ID, appId);
    }
}
